<template>
  <div>
    <h1 style="text-align:center">合并多张图片、下载</h1>
      <div>
        <span>上传背景大图片：</span>
        <input type="file" @change="upBaseImgFn" />
      </div>
      <div>
        <span>上传小图片：</span>
        <input type="file" @change="upSmallImgFn" />
      </div>

      <!-- 图片容器 -->
      <div class="bigWrap" ref="bigWrapRef">
        <img class="bgImg" :src="bigBase64" alt="">

        <div class="smallWrap">
          <img class="smallPic" :src="smallBase64" alt="">
        </div>
      </div>

      <div>
        <button @click="drawProdPicture">下载合并图片</button>
      </div>
  </div>
</template>
<script>
import html2canvas from 'html2canvas'
import { ref, reactive, onMounted, computed } from 'vue'
import axios from 'axios'

export default {
  name: 'AddActivity',
  components: {
  },
  data () {
    return {
      bgPic: bgPic,
      materialUrl: matePic,
      makePic: '',
      bigBase64 : ref(''),
      smallBase64 : ref(''),
      bigWrapRef: ref('')
    }
  },
  created () {
  },
  mounted () {
  },
  methods: {
    upBaseImgFn(){
        // console.log(e.target.files[0])
        let f = e.target.files[0]
        let filereader = new FileReader();
        filereader.onload = function (event) {
          bigBase64.value = event.target.result;
        };
        filereader.readAsDataURL(f);
    },
      // 小图片
     upSmallImgFn () {
        // console.log(e.target.files[0])
        let f = e.target.files[0]
        let filereader = new FileReader();
        filereader.onload = function (event) {
          smallBase64.value = event.target.result;
        };
        filereader.readAsDataURL(f);
      },
    drawProdPicture () {
      // 下载
        console.log(html2canvas(bigWrapRef.value))

        html2canvas(bigWrapRef.value).then(imgbase64 => {
          console.log(imgbase64)
          // .toDataURL()方法是返回一个包含图片展示的 数据URL。可以使用 type 参数其类型
          // .toDataURL(type, encoderOptions);
          let imgUrl = imgbase64.toDataURL("image/png")
          var a = document.createElement('a')
          a.setAttribute('href', imgUrl)
          a.setAttribute('download', 'xxx.png')
          a.click()
          URL.revokeObjectURL(imgUrl)
        })

    }
  }
}
</script>

<style lang='less' scoped>
div {
  margin: 10px 0;
}

.bigWrap {
  width: 400px;
  height: 400px;
  position: relative;
  border: 1px solid #000;
}

img.bgImg {
  width: 100%;
  height: 100%;
}

div.smallWrap {
  width: 100px;
  height: 100px;
  position: absolute;
  top: 30px;
  left: 30px;
  z-index: 9;
  overflow: hidden;
  border: 2px solid rgb(197, 21, 21);
}

div.smallWrap img.smallPic {
  width: 100%;
  height: 100%;
}
</style>

